<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :http-request="uploadImg"
      :before-upload="beforeAvatarUpload"
    >
      <!-- eslint-disable-next-line -->
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProgress" type="circle" :percentage="percent" class="progress" />
    </el-upload>
  </div>
</template>

<script>
const COS = require('cos-js-sdk-v5')
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
const cos = new COS({
  SecretId: 'AKIDnPzKQFn32nPBpIbjdLp45tSo7IG0Y4Rm',
  SecretKey: 'QfgWAoQsAGLQSIaieO9k8Un5B2e4HI6h'
})

export default {
  props: {
    imgUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      showProgress: false,
      percent: 0
    }
  },
  watch: {
    imgUrl(val) {
      this.imageUrl = val
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    uploadImg(e) {
      this.showProgress = true
      /* 直接调用cos sdk的方法 */
      cos.uploadFile(
        {
          Bucket: '23v2-1316034133' /* 填写自己的bucket，必须字段 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: e.file
            .name /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
          Body: e.file, // 上传文件对象
          SliceSize:
            1024 *
            1024 *
            5 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */,
          onProgress: (progressData) => {
            this.percent = Number(progressData.percent * 100)
          }
        },
        (err, data) => {
          if (err) {
            console.log('上传失败', err)
          } else {
            this.showProgress = false
            this.imageUrl = `http://${data.Location}`
            console.log('上传成功')
          }
        }
      )
    },

    handleAvatarSuccess(res, file) {
      console.log(1)
      this.imageUrl = URL.createObjectURL(file.raw)
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
